<template>
    <div style="overflow: auto; ">
        <vxe-table
            :key="tableKey"
            :data="tableData"
            ref="vxeTable"
            keep-source
            :column-config="{ isHover: true }"
            :row-config="{ isHover: true }"
            border
            size="mini"
            style="width: 100%"
            height="100%"
            :auto-resize="true"
            @clear-filter="handleFilterClear"
            :sort-config="{ remote: true, trigger: 'cell', defaultSort: { field: 'thresholdType', order: 'desc' }, orders: ['desc', 'asc', null] }"
            @sort-change="handleSortChange"
            :filter-config="{ remote: true }"
            @filter-change="handleFilterChange"
            header-align="center"
            show-header-overflow
            show-overflow="tooltip"
            resizable
        >
            <vxe-column field="fundCode" title="产品代码" sortable width="120" :filters="[{ data: '' }]" :filter-render="{ name: 'FilterInput' }">
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
            </vxe-column>
            <vxe-column field="fundNameSt" title="产品名称" min-width="120" show-overflow :filters="[{ data: '' }]" :filter-method="filterHandler">
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
            </vxe-column>
            <vxe-column
                field="assetCode"
                title="资产单元编号"
                sortable
                width="160"
                :filters="[{ data: '' }]"
                :filter-render="{ name: 'FilterInput' }"
                v-if="SHOW_SECURITY"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
                <template slot-scope="scope">
                    <span>{{ scope.row.assetCode || '--' }}</span>
                </template>
            </vxe-column>
            <vxe-column
                field="assetName"
                title="资产单元名称"
                min-width="120"
                show-overflow
                :filters="[{ data: '' }]"
                :filter-method="filterHandler"
                v-if="SHOW_SECURITY"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
                <template slot-scope="scope">
                    <span>{{ scope.row.assetName || '--' }}</span>
                </template>
            </vxe-column>
            <vxe-column
                field="fundAccountCode"
                title="组合编码"
                sortable
                width="120"
                :filters="[{ data: '' }]"
                :filter-render="{ name: 'FilterInput' }"
                v-if="SHOW_SECURITY"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
                <template slot-scope="scope">
                    <span>{{ scope.row.fundAccountCode || '--' }}</span>
                </template>
            </vxe-column>
            <vxe-column
                field="fundAccountName"
                title="组合名称"
                min-width="120"
                show-overflow
                :filters="[{ data: '' }]"
                :filter-method="filterHandler"
                v-if="SHOW_SECURITY"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
                <template slot-scope="scope">
                    <span>{{ scope.row.fundAccountName || '--' }}</span>
                </template>
            </vxe-column>

            <vxe-column
                field="stockCode"
                title="证券代码"
                sortable
                show-overflow
                width="150"
                :filters="[{ data: '' }]"
                :filter-method="filterHandler"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
            </vxe-column>
            <vxe-column field="stockNameSt" title="证券名称" show-overflow min-width="120" :filters="[{ data: '' }]" :filter-method="filterHandler">
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
            </vxe-column>
            <vxe-column
                field="entryCode"
                title="条目编号"
                sortable
                width="120"
                show-overflow
                :filters="[{ data: '' }]"
                :filter-render="{ name: 'FilterInput' }"
                :filter-method="filterHandler"
            >
                <template #filter="{ $panel, column }">
                    <el-input
                        class="my-input"
                        type="type"
                        v-for="(option, index) in column.filters"
                        :key="index"
                        v-model="option.data"
                        @input="$panel.changeOption($event, !!option.data, option)"
                    />
                </template>
            </vxe-column>
            <vxe-column field="entryName" title="风险说明" :filters="[{ data: '' }]" :filter-method="filterHandler" show-overflow min-width="130">
                <template #filter="{ $panel, column }">
                    <div>
                        <el-input
                            class="my-input"
                            type="type"
                            v-for="(option, index) in column.filters"
                            :key="index"
                            v-model="option.data"
                            @input="$panel.changeOption($event, !!option.data, option)"
                        />
                    </div>
                </template>
            </vxe-column>
            <vxe-column field="entryType" title="风险类型" show-overflow width="110" :filters="entryTypeArr" column-key="entryType">
                <template slot-scope="scope">
                    <span>{{ entryType[scope.row.entryType] }}</span>
                </template>
            </vxe-column>
            <vxe-column field="thresholdValue" title="风控阈值" width="110" show-overflow>
                <template slot-scope="scope">
                    <span style="float:right">{{
                        scope.row.thresholdValue != undefined
                            ? numberFormat(scope.row.thresholdValue, scope.row.unit) + unitShow(scope.row.unit)
                            : '--'
                    }}</span>
                </template>
            </vxe-column>
            <vxe-column field="compareType2" title="比较方向" width="110" show-overflow> </vxe-column>
            <vxe-column field="calculateValue" title="计算结果(单位)" show-overflow width="120">
                <template slot-scope="scope">
                    <span style="float:right">{{
                            this.WEB_DOCKING === 'CIBFUND' && scope.row.calculateValue != undefined ? numberFormatXDAY(scope.row.calculateValue, scope.row.unit) + unitShow(scope.row.unit) :
                        scope.row.calculateValue != undefined
                            ? numberFormat(scope.row.calculateValue, scope.row.unit) + unitShow(scope.row.unit)
                            : '--'
                    }}</span>
                </template>
            </vxe-column>
            <vxe-column
                field="thresholdType"
                title="阈值类型"
                sortable
                width="130"
                :filters="ThresholdTypeArr"
                :filter-method="filterThresholdType"
                show-overflow
            >
                <!-- <template #filter="{ $panel, column }">
          <el-select
            class="my-select"
            v-model="option.data"
            v-for="(option, index) in column.filters"
            :key="index"
            @change="$panel.changeOption($event, !!option.data, option)"
          >
            <option v-for="(label, cIndex) in ThresholdTypeArr" :key="cIndex" :value="label">{{ label }}</option>
          </el-select>
        </template> -->
                <template slot-scope="scope">
                    <status-tag :code="scope.row.thresholdType" />
                </template>
            </vxe-column>
            <vxe-column field="investableBalance" title="可投余量" min-width="120" show-overflow>
                <template slot-scope="scope">
                    <el-popover
                        v-if="getObjectLength(scope.row.investableBalance) && getObjectLength(scope.row.investableBalance) > 1"
                        placement="top"
                        trigger="hover"
                    >
                        <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row.investableBalance" :key="key">
                            {{ '阀值' + ++index + '可投余量: ' + scope.row['investableBalance']['INVESTABLE_BALANCE_' + index] }}
                        </div>
                        <el-tag slot="reference">{{ getObjectLength(scope.row.investableBalance) + '个可投余量' }}</el-tag>
                    </el-popover>
                    <span v-else v-for="(value, key) in scope.row.investableBalance" :key="key">{{ value }}</span>
                </template>
            </vxe-column>
            <vxe-column field="maxTradable" title="最大可交易量" min-width="120" show-overflow>
                <template slot-scope="scope">
                    <el-popover
                        v-if="getObjectLength(scope.row.maxTradable) && getObjectLength(scope.row.maxTradable) > 1"
                        placement="top"
                        trigger="hover"
                    >
                        <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row.maxTradable" :key="key">
                            {{ '阀值' + ++index + '最大可交易量: ' + scope.row['maxTradable']['MAX_TRADABLE_' + index] }}
                        </div>
                        <el-tag slot="reference">{{ getObjectLength(scope.row.maxTradable) + '最大可交易量' }}</el-tag>
                    </el-popover>
                    <span v-else v-for="(value, key) in scope.row.maxTradable" :key="key">{{ value }}</span>
                </template>
            </vxe-column>
            <vxe-column field="maxTradableMerge" title="最大可交易量(汇总)" min-width="150" show-overflow>
                <template slot-scope="scope">
                    <el-popover
                        v-if="getObjectLength(scope.row.maxTradableMerge) && getObjectLength(scope.row.maxTradableMerge) > 1"
                        placement="top"
                        trigger="hover"
                    >
                        <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row.maxTradableMerge" :key="key">
                            {{ '阀值' + ++index + '最大可交易量(汇总): ' + scope.row['maxTradableMerge']['MAX_TRADABLE_' + index] }}
                        </div>
                        <el-tag slot="reference">{{ getObjectLength(scope.row.maxTradableMerge) + '最大可交易量汇总' }}</el-tag>
                    </el-popover>
                    <span v-else v-for="(value, key) in scope.row.maxTradableMerge" :key="key" style="float:right">{{ value }}</span>
                </template>
            </vxe-column>
            <vxe-column field="entryKey" title="静态条目KEY" show-overflow width="120"> </vxe-column>
            <vxe-column field="branchNum" title="分支详情" show-overflow width="120">
                <template slot-scope="scope">
                    <branch-tag :data="scope.row" />
                </template>
            </vxe-column>
        </vxe-table>
        <div class="block" v-if="tableData.length">
            <el-pagination
                background
                @current-change="pageChangeResult"
                layout="total, prev, pager, next"
                :total="page.total"
                :page-size="page.pageSize"
                :current-page.sync="page.currentPage"
            >
            </el-pagination>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
// import RiskTable from '@/common/components/risk-table.vue';
import { SGU_CACHE, objToArr } from '@/utils/diction-const-util';
import Invest from '@/common/dict/invest';
import { getCurrentPageData, UUID, numberFormat, unitShow, sortBy, getConfigItem, numberFormatXDAY } from '@/utils/tools';
import StatusTag from './status-tag.vue';
import BranchTag from './branch-tag.vue';
import VXETable from 'vxe-table';

// 创建一个简单的输入框筛选
VXETable.renderer.add('FilterInput', {
    // 筛选模板
    // renderFilter(h, renderOpts, params) {
    //     return [`<filter-input params=${params}></filter-input>`];
    // },
    // 重置数据方法
    filterResetMethod({ options }) {
        options.forEach(option => {
            option.data = '';
        });
    },
    // 重置筛选复原方法（当未点击确认时，该选项将被恢复为默认值）
    filterRecoverMethod({ option }) {
        option.data = '';
    },
    // 筛选方法
    filterMethod({ option, row, column }) {
        const { data } = option;
        const cellValue = row[column.property];
        if (cellValue) {
            return cellValue.indexOf(data) > -1;
        }
        return false;
    },
});

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'RiskResult',
    components: { StatusTag, BranchTag },
})
export default class RiskResult extends Vue {
    numberFormat = numberFormat;
    unitShow = unitShow;
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    @Prop()
    riskResultTable: any[];
    @Prop()
    stockInfoPojo: any;

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    resultData: any[] = [];
    resultDataAll: any[] = [];
    // @Prop()
    tableKey: number = 0;
    Invest: any = new Invest();
    entryTypeArr: any[] = [];
    ThresholdTypeArr: any[] = [];
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    private renderUUID: any;

    // 图标dom
    private iconDom: any = null;

    private page: pages = {
        total: 0,
        pageSize: 10,
        currentPage: 1,
    };
    private tableData: any[] = [];

    // 筛选之后分页的数据
    filterDatas: any[] = [];
    // 筛选之后未分页的数据
    filterCacheDatas: any[] = [];

    isFilter: boolean = false;
    property: string = '';
    option: any = {};
    datas: any[];

    resultFilterList: any[] = [];
    filterRiskResultTable: any[] = [];
    resultSortList: any[] = [{ order: 'desc', property: 'thresholdType' }];

    @Watch('riskResultTable', { immediate: true, deep: true })
    onWatchrRiskResultTable() {
        this.resultData = this.riskResultTable.map((item, i) => {
            return {
                ...item,
                key: item.groupCode + '-' + item.groupIndex + '-' + item.entryCode + '-' + item.requestId,
                stockNameSt: this.stockInfoPojo.stockNameSt || (this.stockInfoPojo || {})[item.stockCode] || '',
            };
        });
        this.filterRiskResultTable = this.resultData;
        if (this.resultFilterList.length) {
            this.resultFilterList.forEach(ele => {
                if (['entryType', 'thresholdType'].includes(ele.property)) {
                    this.filterRiskResultTable = this.filterRiskResultTable.filter(row => {
                        return ele.values.includes(row[ele.property]);
                    });
                } else {
                    this.filterRiskResultTable = this.filterRiskResultTable.filter(row => {
                        return row[ele.property].includes(ele.datas);
                    });
                }
            });
        }
        this.pageChangeResult(1);
    }

    mounted() {
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType);
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;

        this.changeTable();
        this.tableKey++;
        this.renderUUID = UUID();
    }

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    changeTable() {
        this.$nextTick(() => {
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.vxe-icon--funnel');
                for (let i = 0; i < 6; i++) {
                    this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                }
            }
        });
    }
    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        this.property = property;
        this.option = option;
        if (row[property].includes(option.data)) {
            this.filterDatas.push(row);
        }
        return row[property].includes(option.data);
    }

    handleFilterClear() {
        // this.filterDatas = [];
    }

    currentChange(val: number) {
        if (this.resultData && this.resultData.length) {
            this.page.total = this.resultData.length;
        } else {
            this.page.total = 0;
        }
        // this.page.total = this.tableData.length ? this.tableData.length : 0;
        this.page.currentPage = val;
        this.tableData = getCurrentPageData(this.resultData, this.page.currentPage, this.page.pageSize);
    }

    // 试算结果表排序
    handleSortChange({ column, property, order, sortBy, sortList, $event }) {
        this.resultSortList = sortList;
        this.pageChangeResult(1);
    }

    // 试算结果表筛选
    handleFilterChange({ column, property, values, datas, filterList, $event }) {
        this.resultFilterList = filterList;
        this.filterRiskResultTable = this.resultData;
        if (this.resultFilterList.length) {
            this.resultFilterList.forEach(ele => {
                if (['entryType', 'thresholdType'].includes(ele.property)) {
                    this.filterRiskResultTable = this.filterRiskResultTable.filter(row => {
                        return ele.values.includes(row[ele.property]);
                    });
                } else {
                    this.filterRiskResultTable = this.filterRiskResultTable.filter(row => {
                        return row[ele.property].includes(ele.datas);
                    });
                }
            });
        }

        this.pageChangeResult(1);
    }

    // 分页
    pageChangeResult(curPage: number): void {
        this.page.currentPage = curPage;
        let data = [];
        // 带筛选条件分页
        if (this.resultFilterList.length) {
            data = JSON.parse(JSON.stringify(this.filterRiskResultTable));
            this.page.total = this.filterRiskResultTable.length ? this.filterRiskResultTable.length : 0;
            // 排序
            console.log(this.resultSortList, 'hhhhhhh');

            if (this.resultSortList.length) {
                data = this.customSortMethod(data, this.resultSortList);
            }
            this.tableData = getCurrentPageData(data, this.page.currentPage, this.page.pageSize);
            this.tableKey++;
        } else {
            data = JSON.parse(JSON.stringify(this.resultData));
            // 不带筛选条件分页
            this.page.total = this.resultData.length ? this.resultData.length : 0;
            // 排序
            console.log(this.resultSortList, 'kkkkkkkkkk');
            if (this.resultSortList.length) {
                data = this.customSortMethod(this.resultData, this.resultSortList);
            }
            this.tableData = getCurrentPageData(data, this.page.currentPage, this.page.pageSize);
        }

        // (this.$refs.vxeTable as any).reloadData(this.tableData);
    }

    customSortMethod(data, sortList) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode.match('.*[A-Z]+.*') || ele.entryCode.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode') {
                YHList.sort(this.compare('entryCode'));
                NoYHlist.sort(this.compare('entryCode'));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(sortBy(property, order));
            }
        }
        // console.log(list, 'sort');

        return list;
    }

    compare(property) {
        return function(a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }
}
</script>
<style lang="scss" scoped>
@import '../style/measure';
.my-input {
    margin: 10px;
    width: 150px;
}
</style>
